<?php
namespace app\middleware;

use app\service\JwtService;
use app\api\controller\center\Auth;
use think\facade\Request;

class JwtAuth
{
    public function handle($request, \Closure $next)
    {
        // 获取Token
        $token = $request->header('Authorization');
        if (!$token) {
            return json(['code' => 401, 'message' => 'Token不能为空']);
        }
        
        // 检查Token是否在黑名单中
        if (Auth::isTokenInBlacklist($token)) {
            return json(['code' => 401, 'message' => 'Token已失效']);
        }
        
        try {
            // 验证Token
            $data = JwtService::verifyToken($token);
            $request->user = $data['data'];
        } catch (\Exception $e) {
            return json(['code' => 401, 'message' => $e->getMessage()]);
        }
        
        return $next($request);
    }
}